﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace IsmsExplorer.Infrastructure.DomainBase {
    public abstract class EntityBase {
        // ************************************ Data ***************************************
        private int _id;
        /// <summary>
        /// The unique identifier for an entity.
        /// </summary>
        public virtual int ID {
            get { return _id; }
            // NOTE: when persisting a new item we assign back its database ID 
            //       hence allowing setting of.
            set { _id = value; }
        }

        public EntityBase() : this(0) {
        }

        public EntityBase(int id) {
            this._id = id;
        }

        #region Equality tests        
        /// <summary>
        /// Equality based on two entities being of same type AND having the same id!
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public override bool Equals(object obj) {
            if (obj == null || !(obj is EntityBase)) {
                return false;
            }
            return (this == (EntityBase)obj);
        }

        /// <summary>
        /// Equality based on two entities being of same type AND having the same id!
        /// </summary>
        /// <param name="l"></param>
        /// <param name="r"></param>
        /// <returns></returns>
        public static bool operator == (EntityBase l, EntityBase r) {
            // NOTE: need the cast, otherwise infinite loop!
            if (((object)l == null) && ((object)r == null)) {
                return true;
            }

            if (((object)l == null) || ((object)r == null)) {
                return false;
            }

            if (l.GetType() != r.GetType()) { 
                return false; 
            }

            if (l.ID != r.ID) { 
                return false; 
            }

            return true;
        }

        /// <summary>
        /// Equality based on two entities being of same type AND having the same id!
        /// </summary>
        /// <param name="l"></param>
        /// <param name="r"></param>
        /// <returns></returns>
        public static bool operator != (EntityBase l, EntityBase r) {
            return !(l == r);
        }

        #endregion

        public override int GetHashCode() {
            return _id.GetHashCode();
            //if (_id != null) {
            //    return this._id.GetHashCode();
            //} else {
            //    throw new InvalidOperationException("Cannot get hash code - Entity id is null");
            //}
        }

    } // end public abstract class EntityBase 
}
